package com.ecld.grpc.client;

import com.ecld.grpc.grpc.*;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GRpcClient {

    private static final Logger logger = Logger.getLogger(GRpcClient.class.getName());
    private final ManagedChannel channel;
    private final AuthServiceGrpc.AuthServiceBlockingStub blockingStub;


    public GRpcClient(String host, int port) {
        ManagedChannelBuilder channelBuilder = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true);
        channel = channelBuilder.build();
        blockingStub = AuthServiceGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }


    public Token doAuthRequest(String uname,String passwd) {
        logger.info("GRPC Client try get token for user "+uname);
        AuthRequest request = AuthRequest.newBuilder().setUname(uname).setPasswd(passwd).build();
        AuthResponse response;
        try {
            response = blockingStub.auth(request);
            logger.info("GRPC Client get a response token=[" + response.getToken().getToken()+"] err=["+response.getErr()+"]");
            return response.getToken();
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "GRPC Client failed: {0}", e.getStatus());
        }
        return null;
    }

    public void doAuthTokenRequest(Token token) {
        logger.info("GRPC Client try auth using token for user "+token.getUser());
        AuthTokenRequest request = AuthTokenRequest.newBuilder().setToken(token).build();
        AuthTokenResponse response;
        try {
            response = blockingStub.authToken(request);
            logger.info("GRPC Client get a response err=[" + response.getErr()+"] valid=["+response.getValid()+"]");
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "GRPC Client failed: {0}", e.getStatus());
        }
    }

    public void doChangePassRequest(String uname,String passwd,String newPasswd) {
        logger.info("GRPC Client try change passwd for user "+uname);
        ChangePassRequest request = ChangePassRequest.newBuilder().setUname(uname).setPasswd(passwd).setNewPasswd(newPasswd).build();
        ChangePassResponse response;
        try {
            response = blockingStub.changePass(request);
            logger.info("GRPC Client get a response err=[" + response.getErr()+"]");
        } catch (StatusRuntimeException e) {
            logger.log(Level.WARNING, "GRPC Client failed: {0}", e.getStatus());
        }
    }


}
